import React, { Component } from 'react'
import store from '../../store'
import axios from 'axios'


// redux是一个独立的库 (html, react, vue)
export default class Car extends Component {
    constructor() {
        super()
        store.subscribe(() => {
            this.setState({})
            console.log('redux中数据更新了')
            console.log(store.getState())
        })
    }
    add = () => {
        store.dispatch({ type: "ADD" })
    } 
    del = () => {
        store.dispatch({ type: "DEL" })
    } 
    init = () => {
        // store.dispatch   经常thunk中间件包装以后的dispatch
        store.dispatch((next) => {
            // next   代表没有经过中间件包装以后的dispatch
            axios.get('/api/getList').then(res => {
                //  store.dispatch
                next({ type: "INIT", list: res.data.list })
            })
        })
    }
    render() {
        return (
            <div>
                 <button onClick={() => {
                    this.del()
                }}>----</button>
                购物车 --- { store.getState().count }
                <button onClick={() => {
                    this.add()
                }}>+++</button>
                <div>
                    { store.getState().list.map(item => {
                        return <div key = { item.id }>
                            { item.title }
                        </div>
                    }) }
                </div>
                <div>
                    <button onClick={ this.init }>发起请求</button>
                </div>
            </div>
        )
    }
}
